//
//  shallow_deep_copy.hpp
//  learnC++
//
//  Created by liuzhibing on 2018/6/7.
//  Copyright © 2018年 yunfan.com. All rights reserved.
//

#ifndef shallow_deep_copy_hpp
#define shallow_deep_copy_hpp

#include <stdio.h>
#include <iostream>
#include <cstring>
#include <cassert>
#include <array>

class MyString3
{
private:
    char *m_data;
    int m_length;
    
    //测试std::Array,结果：这样是可以的，复制构造函数或operator=，复制的对象为该指针，也就是说二者的p指针指向的内存空间是一致的
    std::array<int, 4>  *m_test;
    
public:
    MyString3(const char *source="")
    {
        assert(source); // make sure source isn't a null string
        
        // Find the length of the string
        // Plus one character for a terminator
        m_length = static_cast<int>(strlen(source) + 1);
        
        // Allocate a buffer equal to this length
        m_data = new char[m_length];
        
        // Copy the parameter string into our internal buffer
        for (int i=0; i < m_length; ++i)
            m_data[i] = source[i];
        
        // Make sure the string is terminated
        m_data[m_length-1] = '\0';
        
        m_test = new std::array<int, 4>{1,2,3};
        
        (*m_test)[0] = 0;
    }
    
    //复制构造函数
    MyString3(const MyString3 &source);
    
    //成员操作符 operator=
    MyString3& operator=(const MyString3 &source);
    
    //关于
    //MyString3 m2 = m1;调用的是复制构造函数，没有初始化就是复制构造函数，初始化过就是调用operator=
    
    ~MyString3() // destructor
    {
        // We need to deallocate our string
        delete[] m_data;
        delete [] m_test;
        std::cout << "~MyString3";
    }
    
    char* getString() { return m_data; }
    int getLength() { return m_length; }
};

/*
 
 MyString3 hello("hello,world");
 {
 MyString3 copy = hello; // use default copy constructor
 }// copy is a local variable, so it gets destroyed here.  The destructor deletes copy's string, which leaves hello with a dangling pointer
 std::cout << hello.getString() << "\n";
 
 如何避免：书写自己的复制构造函数和重写operator=
 
 MyString3 m1("hello");
 {
 
 //        MyString3 m2(m1);
 MyString3 m3("kkk");
 m3 = m1;
 //        std::cout << m2.getString();
 }
 
 */

#endif /* shallow_deep_copy_hpp */
